<template>
  <el-dialog
    :title="{ add: '新增部门', edit: '编辑部门' }[mode]"
    width="600px"
    :visible.sync="isShow"
    @close="closeEvent"
  >
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item prop="name" label="部门名称">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item prop="code" label="部门编码">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item prop="manager" label="部门负责人">
        <el-select v-model="form.manager" @focus="focusEvent">
          <el-option
            v-for="i in managerList"
            :key="i.id"
            :label="i.username"
            :value="i.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item prop="introduce" label="部门介绍">
        <el-input v-model="form.introduce" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align: center">
        <el-button @click="cancelEvent">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import {
  sysUserSimple,
  companyDepartmentPost,
  companyDepartmentPut
} from '@/api/departments'
export default {
  props: {
    initList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      mode: 'add',
      isShow: false,
      managerList: [],
      form: {
        name: '', // string	非必须		部门名称
        code: '', // string	非必须		部门编码，同级部门不可重复
        manager: '', // string	非必须		负责人名称
        introduce: '', // string	非必须		介绍
        pid: '' // string	非必须		父级部门ID
      },
      rules: {
        name: [
          { required: true, message: '必填', trigger: 'change' },
          { min: 1, max: 50, message: '请输入1-50个字符', trigger: 'change' },
          {
            validator: (rules, value, callback) => {
              let resultArr = []
              if (this.mode === 'add') {
                resultArr = this.initList.filter((i) => {
                  if (i.pid === this.item.id) {
                    return true
                  }
                })
              } else if (this.mode === 'edit') {
                resultArr = this.initList.filter((i) => {
                  if (i.pid === this.item.id && i.id !== this.item.id) {
                    return true
                  }
                })
              }
              const bol = resultArr.some((i) => {
                // console.log(value)
                return i.name === value
              })
              bol
                ? callback(new Error('请不要输入重复的部门名:' + value))
                : callback()
            }
          }
        ],
        code: [
          { required: true, message: '必填', trigger: 'change' },
          { min: 1, max: 50, message: '请输入1-50个字符', trigger: 'change' },
          {
            validator: (rules, value, callback) => {
              let bol = false
              if (this.mode === 'add') {
                bol = this.initList.some((i) => {
                  return i.code === value
                })
              } else if (this.mode === 'edit') {
                bol = this.initList.some((i) => {
                  return i.code === value && i.id !== this.tiem.id
                })
              }
              bol
                ? callback(new Error('请不要输入重复的部门编码:' + value))
                : callback()
            }
          }
        ],
        manager: [{ required: true, message: '必填', trigger: 'change' }],
        introduce: [
          { required: true, message: '必填', trigger: 'change' },
          { min: 1, max: 50, message: '请输入1-50个字符', trigger: 'change' }
        ]
      },
      item: ''
    }
  },
  // 侦听器
  // watch: {
  //   isShow: {
  //     handler(newVal) {
  //       if (!newVal) {
  //         this.$refs.form.resetFields()
  //       }
  //     }
  //   }
  // },
  mounted() {
    this.$bus.$on('addEvent', (show, item, mode) => {
      this.item = item
      this.isShow = show
      this.mode = mode
      if (mode === 'edit') {
        this.form = JSON.parse(JSON.stringify(item))
      }
    })
  },
  beforeDestroy() {
    this.$bus.$off('addEvent')
  },
  methods: {
    cancelEvent() {
      this.isShow = false
    },
    async focusEvent() {
      if (this.managerList.length === 0) {
        const res = await sysUserSimple()
        this.managerList = res.data
        // console.log(res)
      }
    },
    submit() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          /*
          赋值pid当前点击项的id
          调用新增api，
          成功后关闭弹框
          提示
          刷新父级列表数据
          */
          if (this.mode === 'add') {
            this.form.pid = this.item.id
            await companyDepartmentPost(this.form)
            this.$message.success('添加成功')
          } else if (this.mode === 'edit') {
            await companyDepartmentPut(this.form)
            this.$message.success('修改成功')
          }
          this.isShow = false
          this.$emit('getData')
        }
      })
    },
    closeEvent() {
      this.$refs.form.resetFields()
      this.form = {
        name: '', // string	非必须		部门名称
        code: '', // string	非必须		部门编码，同级部门不可重复
        manager: '', // string	非必须		负责人名称
        introduce: '', // string	非必须		介绍
        pid: '' // string	非必须		父级部门ID
      }
    }
  }
}
</script>

<style></style>
